import { createRouter, createWebHistory, type Router } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useMenuStore } from '@/stores/menu'
import { watchEffect } from 'vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录
    {
      path: '/login/',
      name: 'login',
      component: () => import('../views/auth/login.vue')
    },

    // 主页
    {
      path: '/',
      name: 'home',
      meta: {
        requiresAuth: true // 需要登录才能访问
      },
      component: () => import('../views/home/index.vue'),

      // 子模块
      children: [
        {
          path: 'loading/:to?',
          name: 'adminLoading',
          component: () => import('@/components/loading.vue')
        }
      ]
    },

    /** 
     * 找不到页面，可能是路由还未加载上
     * 
     * 统一重定向到 Loading 页，并将目标页面的参数传递过去。 
     * 等路由从后端请求并初始化完成。系统会自动从 Loading 页跳转回目标页
     * */
    {
      path: '/admin/:pathMatch(.*)*',
      meta: {
        requiresAuth: true // 需要登录才能访问
      },
      redirect: (to) => {
        return {
          name: 'adminLoading',
          params: {
            to: JSON.stringify({
              path: to.path,
              query: to.query,
              hash: to.hash
            })
          }
        }
      }
    },

    // 404 处理
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    },
    {
      path: '/404',
      name: 'notFound',
      component: () => import('@/views/error/404.vue')
    }
  ],
})

// 导航守卫
router.beforeEach(async (to, from) => {
  const userStore = useUserStore();

  // 未登录，跳转到登录页  
  if (to.meta.requiresAuth && !userStore.isAuth) {
    return {
      path: '/login/',
      query: { redirect: to.fullPath }
    }
  }

  await dynamicsRouterLoad(to);
});

/**
 * 动态路由加载
 */
async function dynamicsRouterLoad(to: any) {
  const menuStore = useMenuStore();
  if (menuStore.remoteRouteLoaded) {
    return;
  }

  // 引入指定目录的所有组件，再按照 key 取出来
  const modules = import.meta.glob('@/views/**/*.vue');

  watchEffect(() => {
    let routerInfo = menuStore.routerInfo;
    if (!routerInfo || routerInfo.length === 0) {
      return;
    }

    for (let routerItem of routerInfo) {
      router.addRoute('home', {
        path: routerItem.routerPath ?? '',
        component: modules[routerItem.componentPath ?? '']
      });
    }

    menuStore.remoteRouteLoaded = true;
  })
  
}

export default router
